package com.net.xpay.common.helper;

import com.net.common.util.HttpClientUtil;
import com.net.xpay.core.CoreProperties;
import com.net.xpay.core.helper.EnvironmentHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 2019/8/8 12:04

 */
@Slf4j
@Component
public class NoticeHelper {


    @Autowired
    private EnvironmentHelper environmentHelper;

    @Autowired
    private CoreProperties coreProperties;


    //警告级别 magType 可选 text 、 markdown
    public void sendSystemMonitorNotice(String content, String msgType) {
        sendNotice(content, msgType, coreProperties.getSystemMonitorWebhook());
    }

    //通知级别
    public void sendSystemInfoNotice(String content, String msgType) {
        sendNotice(content, msgType, coreProperties.getSystemInfoWebhook());
    }

    //审核通知
    public void sendAuditNotice(String content, String msgType) {
        sendNotice(content, msgType, coreProperties.getAuditWebhook());
    }

    private void sendNotice(String content, String msgType, String webhook) {
        if (environmentHelper.isDevOrLocal()) {
            log.info("no prod env, no sendNotice");
            return;
        }
        try {
            HttpPost httppost = new HttpPost(webhook);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");
            String textMsg = "{\n" +
                    "        \"msgtype\": \"" + msgType + "\",\n" +
                    "        \"" + msgType + "\": {\n" +
                    "            \"content\": \"" + content +  "\"" +
                    "        }\n" +
                    "   }";
            StringEntity se = new StringEntity(textMsg, "utf-8");
            httppost.setEntity(se);
            String resp = HttpClientUtil.getInstance().executeAndGet(httppost, null, "UTF-8");
            log.info("sendNotice|resp={}", resp);
        } catch (Throwable e) {
            log.error("sendNotice error", e);
        }
    }

}
